/**
 * Created by Administrator on 2016/10/9.
 */
import { notification, Modal } from 'antd';
import * as axios from 'axios';
axios.defaults.baseURL = window.GLOBAL.baseURL;
axios.defaults.headers.post['Content-Type'] = window.GLOBAL.contentType;

//添加 或 编辑 商品信息。
export function addOrEditProduct(obj, paramData) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }
    axios.post('/webAPI/product/addOrEditProduct', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({updateLoading: false, addProductPage: false});

          if(obj.refs["tableView"] == undefined){
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '商品 编辑 成功。',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
            findProductDetial(obj, obj.props.routeParams.id);
          }else {
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '商品 添加 成功。',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
            obj.refs["tableView"].refreshData();
          }
        }
    }).catch(function(err){
        obj.setState({updateLoading: false});
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，网络请求错误。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//修改商品状态
export function changeStatus(obj, paramData, flag) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }
    axios.post('/webAPI/product/addOrEditProduct', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(flag == "manage"){
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '状态修改成功（状态：' + ((response.data.data.status == "inactive")?"禁用":"启用") + '）!',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
            obj.refs["tableView"].refreshData();
          }else if(flag == "detail"){
            obj.setState({updateLoading: false, addProductPage: false});
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '状态修改成功（状态：' + ((response.data.data.status == "inactive")?"禁用":"启用") + '）!',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
            findProductDetial(obj, obj.props.routeParams.id);
          }
        }
    }).catch(function(err){
        obj.setState({updateLoading: false});
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，网络请求错误。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//修改商品，关联信息
export function modifyRelatedProducts(obj, paramData, flag) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }
    axios.post('/webAPI/product/addOrEditProduct', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(flag == "delete"){
            obj.setState({productList: false, tempProductData: []},() => {
              Modal.success({
                title: '提示：',
                content: '删除成功，目前还有：' + paramData.relatedProductsIds.length + ' 个关联'
              });
              findProductDetial(obj, obj.props.routeParams.id);
            });
          }else if(flag == "add"){
            obj.setState({productList: false, tempProductData: []},() => {
              Modal.success({
                title: '提示：',
                content: '已成功关联：' + paramData.relatedProductsIds.length + ' 个商品'
              });
              findProductDetial(obj, obj.props.routeParams.id);
            });
          }
        }
    }).catch(function(err){
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，网络请求错误。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//查找商品详情信息
export function findProductDetial(obj, id) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }
    axios.post('/webAPI/product/findProductDetial/' + id, null)
    .then(function (response) {
        if(response.data.code == 1){
            obj.setState({productDetial: response.data.data});
        }
    })
}

//上传商品图片
export function addOrEditProductPic(obj, id, file) {
  obj.setState({ loading: true, tipUpdate: "Update picture..." });

  var formData = new FormData();
  formData.append("id", id);
  formData.append("pic", file);
  $.ajax({
    url: GLOBAL.baseURL + "webAPI/product/addOrEditProductPic",
    type: "POST",
    cache: false,
    data: formData,
    dataType: "json",
    headers: {
      Accept: "*/*",
      'X-Requested-With': 'XMLHttpRequest',
      staffAuth: sessionStorage.getItem('staffAuth')
    },
    contentType: "multipart/form-data",
    processData: false,  // 告诉jQuery不要去处理发送的数据
    contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
    success: function(response){
        if(response.code == 1){
          obj.state.productDetial.product = response.data;
          obj.setState({loading: false});

          Modal.success({
            title: '提示：',
            content: '图片上传 成功。'
          });
        }
    },
    error: function(err){
      obj.setState({ loading: false });
      Modal.error({
        title: '提示：',
        content: '图片上传 失败。'
      });
    }
  });
}

//添加图文信息
export function editImageText(obj, paramData) {
    var formData = new FormData();
    for (var item in paramData) {
      formData.append(item, paramData[item]);
    }
    if ($("#filePic")[0].files.length >= 1){
        formData.append("pic", $("#filePic")[0].files[0]);
    }
    $.ajax({
      url: GLOBAL.baseURL + "webAPI/product/editImageText",
      type: "POST",
      cache: false,
      data: formData,
      dataType: "json",
      headers: {
        Accept: "*/*",
        'X-Requested-With': 'XMLHttpRequest',
        staffAuth: sessionStorage.getItem('staffAuth')
      },
      contentType: "multipart/form-data",
      processData: false,  // 告诉jQuery不要去处理发送的数据
      contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
      success: function(response){
          if(response.code == 1){
            obj.setState({updateImageLoading: false, updateImageVisible: false}, ()=>{
              findProductDetial(obj, obj.props.routeParams.id);
              Modal.success({
                title: '提示：',
                content: '图文信息，提交成功!'
              });
            });
          }
      },
      error: function(err){
        obj.setState({ updateImageLoading: false });
        Modal.error({
          title: '提示：',
          content: '图文信息，提交失败!'
        });
      }
    });
}
//删除图文信息
export function removeImageText(obj, paramData) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }
    axios.post('/webAPI/product/removeImageText', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          for (var i = 0; i < obj.state.productDetial.imageTextList.length; i++) {
              var imageText = obj.state.productDetial.imageTextList[i];
              if(imageText.id == paramData.itId){
                  var temp = obj.state.productDetial.imageTextList.splice(i, 1);
              }
          }
          obj.setState({deleteImageLoading: false});
          Modal.success({
            title: '提示：',
            content: '图文信息，删除成功!'
          });
        }
    }).catch(function(err){
        obj.setState({deleteImageLoading: false});
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，网络链接错误。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//删除图文信息（图片）
export function removeImageTextPic(obj, itId, index) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }

    axios.post('/webAPI/product/removeImageTextPic?id=' + itId, null)
    .then(function (response) {
        if(response.data.code == 1){
          for (var i = 0; i < obj.state.productDetial.imageTextList.length; i++) {
              var imageText = obj.state.productDetial.imageTextList[i];
              if(imageText.id == itId){
                  delete imageText.pic; break;
              }
          }
          obj.setState({productDetial: obj.state.productDetial},() => {
            obj.refs["imageText_" + index].setState({spinning: false});

            Modal.success({
              title: '提示：',
              content: '图片 删除 成功!'
            });
          });
        }
    }).catch(function(err){
        obj.refs["imageText_" + index].setState({spinning: false});
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，网络链接错误。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//文章图文排序接口
export function adjustImageTextOrder(obj, pId, paramData) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }

    axios.post('/webAPI/product/adjustImageTextOrder/' + pId, paramData)
    .then(function (response) {
        if(response.data.code == 1){
            if(response.data.data.length > 0){
                obj.setState({orderUpdating: false});
                findProductDetial(obj, obj.props.routeParams.id);
                notification.success({
                    placement: 'bottomRight',
                    message: '提示：',
                    description: "排序成功，自动刷新。",
                    style: {
                      borderLeft: '4px solid rgb(23, 168, 84)'
                    }
                });
            }
        }
    }).catch(function(err){
        obj.setState({orderUpdating: false});
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，服务器连接错误，请联系相关管理人员。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//查找用户详情
export function findUserDetail(obj, uId) {
    if(sessionStorage.getItem("staffAuth") != null){
        axios.defaults.headers.common['staffAuth'] = sessionStorage.getItem('staffAuth');
    }

    axios.post('/webAPI/user/findUserDetail/' + uId, null)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({userProfile: response.data.data.userProfile, shoppingCartList: response.data.data.shoppingCartList});
        }
    }).catch(function(err){
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: '对不起，服务器连接错误，请联系相关管理人员。',
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
// /webAPI/feedback  /findFeedbacks
